package com.jimikongjian.filter;

import com.alibaba.fastjson.JSON;
import com.jimikongjian.models.ErrorMessage;
import com.jimikongjian.models.Message;
import com.jimikongjian.models.ResponseMessage;
import com.jimikongjian.models.Token;
import com.jimikongjian.service.TokenService;
import com.jimikongjian.service.message.ResponseMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by fuxiuyang on 17-5-8.
 */
@Configuration
public class TokenFilter implements HandlerInterceptor {

    @Autowired
    @Qualifier("tokenService")
    private TokenService tokenService;

    @Autowired
    @Qualifier("responseMessageService")
    private ResponseMessageService responseMessageService;

    /**
     * 获取请求的token，验证token，如果验证成功则继续往下执行，如果不成功则停止执行
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        String authentication = httpServletRequest.getHeader("Authentication");
        System.out.println("Authentication:"+authentication);
        String email = httpServletRequest.getHeader("Email");
        System.out.println("email:"+email);

        String method = httpServletRequest.getMethod();
        Token token = new Token();
        token.setToken(authentication);
        token.setEmail(email);

        if (!method.toUpperCase().equals("OPTIONS")) {
            if (authentication == null || authentication.equals("null") || email == null || email.equals("null") || !tokenService.checkToken(token)) {
                    httpServletResponse.setStatus(401);
                    String js = JSON.toJSONString(httpServletResponse.getStatus());
                    PrintWriter pt = httpServletResponse.getWriter();
                    pt.print(js);
                    return false;
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
